package itsm.isperp.module.controller.customer;

import itsm.isperp.framework.collection.tree.ITreeNode;
import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.dialect.DialectFactory;
import itsm.isperp.framework.data.domain.DataResponse;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.data.mybatis.domain.AbstractTreeNode;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.web.controller.BaseController;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.entity.app.AppDepartment;
import itsm.isperp.module.entity.configuration.ConfCi;
import itsm.isperp.module.entity.customer.CusCustomer;
import itsm.isperp.module.service.app.AppDepartmentService;
import itsm.isperp.module.service.app.AppDictService;
import itsm.isperp.module.service.customer.CusCustomerService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("customer/customer")
public class CusCustomerController extends BaseController<CusCustomer> {

  /**
   * 
   */
  @Autowired
  protected CusCustomerService cusCustomerService;

  @Autowired
  protected AppDictService appDictService;

  @Autowired
  protected AppDepartmentService appDepartmentService;

  @Override
  public CusCustomerService getService() {
    return cusCustomerService;
  }

  @Override
  public String getPageTitle() {
    return "客户资料";
  }

  /**
   * 客户编辑界面
   * 
   * @return 客户编辑界面视图
   */
  @RequestMapping("edit")
  @Override
  public ModelAndView edit(String id, HttpServletRequest req) {
    ModelAndView mv = new ModelAndView();
    String hideBtn = req.getParameter("hideBtn");
    String type = req.getParameter("type");
    JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
    if (StringUtils.isNotBlank(hideBtn)) {
      mv.addObject("hideBtn", hideBtn);
    }
    if (StringUtils.isNotBlank(type)) {
      mv.addObject("type", type);
      if (type.equals("0")) {
        String sql1 = "SELECT * FROM cus_customer WHERE category='company' limit 1 ";
        List<Map<String, Object>> list1 = jdbcTemplate.queryForList(sql1);
        if (list1.size() > 0) {
          id = list1.get(0).get("id").toString();
        }
      } else {
        mv.setViewName("customer/customer/providerEdit");
      }
    }

    if (StringUtils.isEmpty(id)) {
      mv.addObject("newEdit", "true");
      CusCustomer cus = new CusCustomer();
      String tid = HibernateUUIDGenerator.generate();
      cus.setId(tid);
      mv.addObject("model", cus);
    } else {
      CusCustomer cus = this.getService().findOne(id);
      mv.addObject("model", cus);
      mv.addObject("newEdit", "false");
      String sql1 = "select * from app_department where id=(select department_id from cus_customer where id='"
          + id + "')";
      List<Map<String, Object>> list1 = jdbcTemplate.queryForList(sql1);
      if (list1.size() > 0) {
        String treenode_name_path = list1.get(0).get("treenode_name_path")
            .toString();
        mv.addObject("treenode_name_path", treenode_name_path);
      }
    }

    mv.addObject("customer_type", appDictService.findByType("CUSTOMER_TYPE"));
    mv.addObject("area_code", appDictService.findByType("AREA_CODE"));

    return mv;
  }

  @Override
  @RequestMapping("save")
  @ResponseBody
  public ResultMessage save(CusCustomer model, HttpServletRequest req) {

    // 得到一条数据
    CusCustomer oldModel = this.getService().findOne(model.getId());
    JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
    // 判断是否为新增
    String type = req.getParameter("ctype");
    if (oldModel != null) {

      // 更具名字获取一个客户，并且id是不同的
      // 如果存在这样的客户，提示"已经存在相同名称的客户！"
      JqGridRequest request = new JqGridRequest();
      request.isPageable(false);
      request.setSelectColumns("id");
      request.addFilterRule("id", JqGridFilterRuleOp.ne, model.getId());
      request.addFilterRule("name", JqGridFilterRuleOp.eq, model.getName());
      request.isQueryOne(true);

      DataResponse<CusCustomer> res = this.getService().findAll(request);
      if (res.getContent() != null && res.getContent().size() > 0) {
        return ResultMessage.failure("已经存在相同名称的客户！");
      }

    } else {
      String tName = model.getName();
      String tid = model.getId();
      AppDepartment apdt = new AppDepartment();
      apdt.setId(tid);
      apdt.setName(tName);
      apdt.setParentId(null);
      if (StringUtils.isNotEmpty(type) && type.equals("1"))
        apdt.setAreCustomerDept(true);
      AppDepartmentService apdtService = ContextHolder
          .getSpringBean("appDepartmentService");
      apdtService.saveOrUpdate(apdt);
      
    }
    model.setDepartmentId(model.getId());
    model.setDepartmentName(model.getName());
    return super.save(model, req);
  }

  /**
   * 用户的配置库
   * 
   * @param customerId
   *          客户id
   * @return 客户资产库页面
   */
  @RequestMapping("customerCiEdit")
  public ModelAndView customerCiEdit(String customerId) {

    ModelAndView mv = new ModelAndView("customer/customer/customerCiEdit");
    mv.addObject("customerId", customerId);
    return mv;
  }

  @RequestMapping("getCompanyCustomer")
  public CusCustomer getCompanyCustomer() {
    JqGridRequest request = new JqGridRequest();
    request.addFilterRule("category", JqGridFilterRuleOp.eq, "company");
    return this.getService().findOneByRequest(request);
  }

  @RequestMapping("getCustomerCiMenu")
  @ResponseBody
  public List<ITreeNode> getCustomerCiMenu() {
    List<ITreeNode> nodes = new ArrayList<>();
    List<Map<String, Object>> list = this.getService().getCustomerCiCount();

    for (Map<String, Object> map : list) {

      ITreeNode tn = new AbstractTreeNode();
      tn.setName(map.get("name").toString() + "("
          + map.get("count_id").toString() + ")");
      tn.setId(map.get("id").toString());
      tn.setTreenodePath(map.get("id").toString());
      tn.setLeaf(true);
      nodes.add(tn);

    }
    return nodes;
  }

  @RequestMapping("manageEdit")
  public ModelAndView manageEdit(HttpServletRequest req) {
    ModelAndView mv = new ModelAndView("customer/customer/manageEdit");
    String type = req.getParameter("type");
    if (StringUtils.isNotBlank(type))
      mv.addObject("type", type);
    return mv;
  }

  @RequestMapping("listCustomer")
  @ResponseBody
  public PageResponse<Map<String, Object>> listCustomer(JqGridRequest request,
      HttpServletRequest req) {
    String type = req.getParameter("type");
    if (StringUtils.isNotBlank(type)) {
      if (type.equals("0"))
        request.addFilterRule("category", JqGridFilterRuleOp.eq, "company");
      else if (type.equals("1"))
        request.addFilterRule("category", JqGridFilterRuleOp.eq, "customer");
    }
    return this.getService().findAllDetailByRequest(request).toPage();

  }

  @Override
  @RequestMapping("delete")
  @ResponseBody
  public ResultMessage delete(String id, HttpServletRequest req) {
    // 删除关联的部门
    JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
    String sql = "delete from app_department where  name=(select name from cus_customer where id='"
        + id + "')";
    jdbcTemplate.execute(sql);
    this.getService().delete(id);
    return ResultMessage.newInstance(true);
  }

  @RequestMapping("getCustomerByRelateDeptId")
  @ResponseBody
  public Map<String, Object> getCustomerByRelateDeptId(String deptId) {
    return this.getService().getCustomerByRelateDeptId(deptId);
  }

  @RequestMapping("autocompleteList")
  @ResponseBody
  public PageResponse<CusCustomer> autocompleteList(JqGridRequest request,
      HttpServletRequest req) {
    String term = req.getParameter("term");

    if (StringUtils.isNotEmpty(term)) {
      request.isPageable(false);
      request.setRows(10);
      request.setSelectColumns("id", "name");
      request.setGroupBy("id,name");
      request.setSearchString(" (name is not null) and (upper(name) LIKE '%"
          + term.toUpperCase() + "%') ");
    }
    return this.getService().findAll(request).toPage();
  }

}
